<template>
  <Card>
    <div id="outMaterial">
      <div class="title">
        <Icon size="18" type="md-list-box"/>
        物资出库
        <Divider/>
      </div>
      <div class="from">
        <Form ref="form" :label-width="170" :model="form" :rules="formValidate" inline>
          <div class="fromTitle">基础信息</div>
          <Row>
            <Col span="10">
            <Form-item label="出库时间：" prop="out_time">
              <DatePicker
                v-model="form.out_time"
                :editable="false"
                placeholder="选择时间"
                type="datetime"
              ></DatePicker>
            </Form-item>
            </Col>
            <Col span="10">
            <FormItem label="车队：">
              <Select v-model="form.fleet" clearable filterable>
                <Option value="一车队">一车队</Option>
                <Option value="二车队">二车队</Option>
                <Option value="三车队">三车队</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="合计金额：">
              <Input v-model="form.total_money" placeholder="" readonly/>
            </FormItem>
            </Col>
            <Col span="10">
            <FormItem label="经手人审核人员：" prop="handler_user_id">
              <Select v-model="form.handler_user_id" filterable learable>
                <Option
                  v-for="item in userList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.name }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
          <div class="fromTitle">出库详情</div>
          <div class="btns">
            <Button
              :loading="busLoading"
              icon="ios-add"
              target="_self"
              type="primary"
              @click="toAdd"
            >添加
            </Button>
            <Button icon="md-remove" type="error" @click="delAll">删除</Button>
          </div>
          <div style="margin-bottom:15px">
            <Table
              ref="selection"
              :columns="columns"
              :data="dataStart"
              :loading="loading"
              border
              height="350"
              size="small"
              stripe
              @on-selection-change="showSelect($event, 'start')"
            >
              <template slot="action" slot-scope="{ row, index }">
                <a
                  class="edit"
                  size="small"
                  style="color:#2d8cf0;font-size: 12px;"
                  type="text"
                  @click="edit(row)"
                >编辑</a>
                <Divider type="vertical"/>
                <a class="del" style="color:#ed4014;font-size: 12px;" @click="del(row)">删除</a>
              </template>
            </Table>
          </div>
          <div style="height:50px;"></div>
          <div class="fromItem">
            <FormItem label>
              <Button
                :loading="submitLoading"
                icon="md-checkmark-circle"
                style="margin-right:10px"
                type="primary"
                @click="handleSubmit('form')"
              >保存
              </Button>
              <Button
                :loading="submitResetLoading"
                icon="md-checkmark-circle"
                style="margin-right:10px"
                type="primary"
                @click="handleSubmitReset"
              >保存并提交
              </Button>
              <Button icon="md-refresh" type="default" @click="handleReset">重置</Button>
            </FormItem>
          </div>
        </Form>
      </div>
      <Modal
        v-model="modal"
        :mask-closable="false"
        :styles="{top: '20px'}"
        title="添加出库详情"
        width="850"
        @on-cancel="cancel"
      >
        <Form ref="detailForm" :label-width="90" :model="detailForm" :rules="detailFormValidate">
          <Row>
            <Col span="12">
            <FormItem label="物资名称" prop="title">
              <Select v-model="detailForm.title" clearable filterable @on-change="changeMaterial">
                <Option
                  v-for="item in materialList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.title }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="规格" prop="specs">
              <Input v-model="detailForm.specs" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单位" prop="unit_title">
              <Input v-model="detailForm.unit_title" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="单价" prop="price">
              <Input v-model="detailForm.price" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
          </Row>
          <Divider/>
          <Row>
            <Col span="12">
            <FormItem label="数量" prop="amount">
              <Input v-model="detailForm.amount" placeholder="请输入数量"></Input>
            </FormItem>
            </Col>
          </Row>
          <Divider/>
          <Row>
            <Col span="12">
            <FormItem label="是否消耗品">
              <RadioGroup v-model="detailForm.is_consumables">
                <Radio label="0">否</Radio>
                <Radio label="1">是</Radio>
              </RadioGroup>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="线路" prop="line">
              <Select
                v-model="detailForm.line"
                clearable
                filterable
                placeholder="选择线路"
                @on-change="changeLine"
              >
                <Option v-for="item in lines" :key="item.line" :value="item.line">{{ item.line }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车号" prop="bus_num">
              <Select v-model="detailForm.bus_num" clearable filterable placeholder="选择车号">
                <Option v-for="(item,index) in busNums" :key="index" :value="item.license_plate_num">
                  {{ item.license_plate_num }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button :loading="loading" @click="handleReset('detailForm')">重置</Button>
          <Button
            :loading="submitLoading"
            style="margin-left:8px"
            type="primary"
            @click="submitF('detailForm')"
          >保存
          </Button>
        </div>
      </Modal>
      <Modal
        v-model="editModal"
        :mask-closable="false"
        :styles="{top: '20px'}"
        title="编辑出库详情"
        width="850"
        @on-cancel="cancel"
      >
        <Form
          ref="editDetailForm"
          :label-width="90"
          :model="editDetailForm"
          :rules="editDetailFormValidate"
        >
          <Row>
            <Col span="12">
            <FormItem label="物资名称" prop="material_id">
              <Select
                v-model="editDetailForm.material_id"
                clearable
                filterable
                @on-change="changeEditMaterial"
              >
                <Option
                  v-for="item in materialList"
                  :key="item.id"
                  :value="item.id"
                >{{ item.title }}
                </Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="规格" prop="specs">
              <Input v-model="editDetailForm.specs" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="单位" prop="unit">
              <Input v-model="editDetailForm.unit_title" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="单价" prop="price">
              <Input v-model="editDetailForm.price" placeholder="自动完成" readonly></Input>
            </FormItem>
            </Col>
          </Row>
          <Divider/>
          <Row>
            <Col span="12">
            <FormItem label="数量" prop="amount">
              <Input v-model="editDetailForm.amount" placeholder="请输入数量"></Input>
            </FormItem>
            </Col>
          </Row>
          <Divider/>
          <Row>
            <Col span="12">
            <FormItem label="是否消耗品">
              <RadioGroup v-model="editDetailForm.is_consumables">
                <Radio label="0">否</Radio>
                <Radio label="1">是</Radio>
              </RadioGroup>
            </FormItem>
            </Col>
          </Row>
          <Row>
            <Col span="12">
            <FormItem label="线路" prop="line">
              <Select
                v-model="editDetailForm.line"
                clearable
                filterable
                placeholder="选择线路"
                style="width:200px;"
                @on-change="changeLine"
              >
                <Option v-for="item in lines" :key="item.line" :value="item.line">{{ item.line }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车号" prop="bus_num">
              <Select
                v-model="editDetailForm.bus_num"
                clearable
                filterable
                placeholder="选择车号"
                style="width:200px;"
              >
                <Option v-for="(item,index) in busNums" :key="index" :value="item.license_plate_num">
                  {{ item.license_plate_num }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </Row>
        </Form>
        <div slot="footer">
          <Button :loading="loading" @click="cancel('editDetailForm')">重置</Button>
          <Button
            :loading="submitLoading"
            style="margin-left:8px"
            type="primary"
            @click="editSubmitF('editDetailForm')"
          >保存
          </Button>
        </div>
      </Modal>
    </div>
  </Card>
</template>
<script>
import './outMaterial.css'
import {addMaterialDetail, addOutMaterial, getUser, lineBusNum, materialListSelect} from '../../../api/material'
import {dictData} from '../../../api/insure'

export default {
  data() {
    return {
      submitLoading: false,
      submitResetLoading: false,
      submitAddPutLoading: false,
      loading: false,
      busLoading: false,
      form: {},
      detailForm: {},
      formValidate: {
        out_time: [{
          required: true,
          message: '出库时间不能为空',
          trigger: 'blur',
          type: 'date'
        }],
        handler_user_id: [{
          required: true,
          message: '经手人必填',
          trigger: 'chanage',
          type: 'number'
        }]
      },
      editDetailForm: {},
      editDetailFormValidate: {},
      detailFormValidate: {},
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          type: 'index',
          width: 60,
          align: 'center',
          fixed: 'left'
        },
        {
          title: '物资名称',
          key: 'title',
          width: 150,
          align: 'left'
        },
        {
          title: '规格',
          key: 'specs',
          align: 'center'
        },
        {
          title: '单位',
          key: 'unit_title',
          align: 'center'
        },
        {
          title: '数量',
          key: 'amount',
          align: 'center'
        },
        {
          title: '单价',
          key: 'price',
          align: 'right'
        },
        {
          title: '总价',
          key: 'total_price',
          align: 'right'
        },
        {
          title: '是否消耗品',
          key: 'is_consumables_name',
          align: 'center'
        },
        {
          title: '线路',
          key: 'line',
          align: 'left'
        },
        {
          title: '车号',
          key: 'bus_num',
          align: 'center'
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 200,
          align: 'right'
        },
        {
          title: '操作',
          slot: 'action',
          width: 120,
          fixed: 'right',
          align: 'center'
        }
      ],
      dict: [],
      busListData: [],
      index: 0,
      dataStart: [],
      modal: false,
      editModal: false,
      detailList: [],
      total: 2,
      selectCount: 0, // 多选计数
      selectList: [], // 多选数据
      materialList: [],
      detailAddAmount: 0,
      lines: [],
      busNumList: [],
      busNums: [],
      userList: []
    }
  },
  watch: {
    $route: 'init'
  },
  mounted() {
    this.getLineBusNum()
    this.getDictData()
    this.getMaterialList()
    this.getUser()
  },
  methods: {
    cancel() {
      this.$refs.detailForm.resetFields()
    },
    getUser() {
      getUser().then(res => {
        if (res.data.result) {
          this.userList = res.data.result
        }
      })
    },
    changeLine(e) {
      this.busNums = this.busNumList[e]
    },
    changeEditMaterial(e) {
      const _this = this
      this.materialList.forEach(function (v) {
        if (v.id == e) {
          _this.editDetailForm.specs = v.specs
          _this.editDetailForm.unit_title = v.unit_title
          _this.editDetailForm.unit = v.unit
          _this.editDetailForm.price = v.price
          _this.detailAddAmount = v.amount
        }
      })
    },
    changeMaterial(e) {
      const _this = this
      this.materialList.forEach(function (v) {
        if (v.id == e) {
          _this.detailForm.specs = v.specs
          _this.detailForm.unit_title = v.unit_title
          _this.detailForm.unit = v.unit
          _this.detailForm.price = v.price
          _this.detailAddAmount = v.amount
        }
      })
    },
    del(row) {
      this.detailList.splice(row._index, 1)
      let total_money = 0
      for (const i in this.detailList) {
        total_money =
          parseFloat(total_money) + parseFloat(this.detailList[i].total_price)
      }
      this.form.total_money = total_money.toFixed(2)
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要删除的数据')
        return
      }
      const _this = this
      this.selectList.forEach(function (e) {
        _this.detailList.splice(e.index, 1)
        let total_money = 0
        for (const i in _this.detailList) {
          _this.detailList[i].index = i
          total_money =
            parseFloat(total_money) +
            parseFloat(_this.detailList[i].total_price)
        }
        _this.form.total_money = total_money.toFixed(2)
      })
    },
    edit(e) {
      this.editDetailForm = e
      this.busNums = this.busNumList[parseInt(e.line)]
      this.editDetailForm.bus_num = e.bus_num
      this.editModal = true
    },
    // 修改详情
    editSubmitF() {
      this.editDetailForm.is_consumables_name =
        this.editDetailForm.is_consumables === '1' ? '是' : '否'
      this.detailList[this.editDetailForm._index] = this.editDetailForm
      this.detailList[this.editDetailForm._index].total_price = (
        parseFloat(this.editDetailForm.price) *
        parseFloat(this.editDetailForm.amount)
      ).toFixed(2)
      this.dataStart = this.detailList
      let total_money = 0
      for (const i in this.detailList) {
        total_money =
          parseFloat(total_money) + parseFloat(this.detailList[i].total_price)
      }
      this.form.total_money = total_money.toFixed(2)
      this.cancel()
      this.editModal = false
    },
    getDictData() {
      dictData({title: '物资单位'}).then(res => {
        if (res.data.result) {
          this.dict = res.data.result
        }
      })
    },
    getLineBusNum() {
      lineBusNum().then(res => {
        this.lines = res.data.line
        this.busNumList = res.data.bus
      })
    },
    getMaterialList() {
      materialListSelect({type: 'edit'}).then(res => {
        this.materialList = res.data.personnel
      })
    },
    handleReset() {
      this.$refs.form.resetFields()
      this.form = {}
      this.dataStart = this.detailList = []
    },
    handleSubmit(name) {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.detailList = this.detailList
          this.submitLoading = true
          addOutMaterial(this.form).then(res => {
            this.submitLoading = false
            if (res.data) {
              this.$Message.success('保存成功')
              this.$store.commit('closeTag', 'addOutMaterial')
              this.$router.push({
                name: 'outMaterial'
              })
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    handleSubmitReset() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.detailList = this.detailList
          this.form.status = 2
          this.submitResetLoading = true
          addOutMaterial(this.form).then(res => {
            this.submitResetLoading = false
            if (res.data) {
              this.$Message.success('保存成功')
              this.$store.commit('closeTag', 'addOutMaterial')
              this.$router.push({
                name: 'outMaterial'
              })
            } else {
              this.$Message.error('保存失败')
            }
          })
        }
      })
    },
    init() {
      this.form = {}
      this.detailList = []
      this.dataStart = []
      this.getLineBusNum()
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    submitF() {
      this.detailForm.index = this.detailList.length
      const _this = this
      let c_amount = 0
      let i = 0
      this.detailList.forEach(function (v) {
        if (_this.detailForm.title == v.title_id) {
          c_amount = parseInt(c_amount) + parseInt(v.amount)
          i++
        }
      })
      if (i === 0) {
        c_amount = this.detailForm.amount
      }
      if (parseFloat(c_amount) > parseFloat(this.detailAddAmount)) {
        this.$Message.error('物资库存不足')
        return
      }
      this.submitAddPutLoading = true
      addMaterialDetail(this.detailForm).then(res => {
        this.submitAddPutLoading = false
        if (res.data) {
          this.materialList.forEach(function (v) {
            if (v.id === res.data.result.title) {
              res.data.result.material_id = res.data.result.title
              res.data.result.title = v.title
              res.data.result.title_id = v.id
            }
          })
          this.detailList.push(res.data.result)
          let total_money = 0
          for (const i in this.detailList) {
            total_money =
              parseFloat(total_money) +
              parseFloat(this.detailList[i].total_price)
          }
          this.form.total_money = total_money.toFixed(2)
        } else {
          this.$Message.error('没有数据')
        }
      })
      this.dataStart = this.detailList
      this.modal = false
      this.cancel()
    },
    toAdd() {
      this.modal = true
    }
  }
}
</script>
<style>
.ivu-row .ivu-col .ivu-form-item {
  width: 100%;
}
</style>
